package com.thinkingcoder.tcrpc.core.transport;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.thinkingcoder.tcrpc.core.meta.InstanceMeta;

@RestController
@RequestMapping("/registry")
public class MockTcRegistry {

    public static final MultiValueMap<String, InstanceMeta> REGISTRY = new LinkedMultiValueMap<>();
    public static final AtomicLong VERSION = new AtomicLong(0);

    public MockTcRegistry() {
        System.out.println(" =====>>>>>>>>> Mock TcRegistry start ... ");
        System.out.println(" =====>>>>>>>>> MockT cRegistry start ... ");
        System.out.println(" =====>>>>>>>>> MockTc Registry start ... ");
    }

    @RequestMapping("/reg")
    public InstanceMeta reg(@RequestParam("serviceName") String serviceName, @RequestBody InstanceMeta instance) {
        REGISTRY.add(serviceName, instance);
        VERSION.getAndIncrement();
        return instance;
    }

    @RequestMapping("/unReg")
    public InstanceMeta unReg(@RequestParam("serviceName") String serviceName, @RequestBody InstanceMeta instance) {
        REGISTRY.remove(serviceName, instance);
        VERSION.getAndIncrement();
        return instance;
    }

    @RequestMapping("/findAll")
    public List<InstanceMeta> findAll(@RequestParam("serviceName") String serviceName) {
        return REGISTRY.get(serviceName);
    }

    @RequestMapping("/renew")
    public long renew(@RequestParam("serviceName") String serviceName, @RequestBody InstanceMeta instance) {
        return System.currentTimeMillis();
    }

    @RequestMapping("/renews")
    public long renews(@RequestParam("serviceNames") String serviceNames, @RequestBody InstanceMeta instance) {
        return System.currentTimeMillis();
    }

    @RequestMapping("/version")
    public long version(@RequestParam("serviceName") String serviceName) {
        return VERSION.get();
    }

    @RequestMapping("/versions")
    public Map<String, Long> versions(@RequestParam("serviceNames") String serviceNames) {
        return Arrays.stream(serviceNames.split(",")).collect(Collectors.toMap(k -> k, v -> VERSION.get()));
    }
}
